//
//  TableViewController.m
//  AsynImageDownload
//
//  Created by Santiago Fontanarrosa on 6/20/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "TableViewController.h"
#import "CustomCell.h"
#import "SBJson.h"
#import "DataModel.h"

#define kItunesURL @"http://itunes.apple.com/us/rss/topfreeapplications/limit=100/json"

@interface TableViewController ()

@property (nonatomic,retain) NSMutableArray *dataArray;
@property (nonatomic, retain) NSMutableData *responseData;
@property (nonatomic, retain) NSURL *url;
@property (nonatomic, retain) NSURLRequest *request;
@property (nonatomic, retain) NSURLConnection *connection;
@end



@implementation TableViewController

@synthesize dataArray = _dataArray;
@synthesize responseData = _responseData;
@synthesize url = _url;
@synthesize connection = _connection;
@synthesize request = _request;


-(void)dealloc
{
    self.dataArray = nil;
    self.responseData = nil;
    [super dealloc];
}

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.url = [NSURL URLWithString:kItunesURL];
    self.request = [NSURLRequest requestWithURL:self.url];
    self.connection = [[NSURLConnection alloc] initWithRequest:self.request delegate:self];
    
    [self.connection start];
    
    self.responseData = [NSMutableData data];
    _dataArray = [[NSMutableArray alloc] init];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.dataArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    CustomCell *cell = (CustomCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (!cell) {
        cell = [CustomCell newCustomCell];
    }
    DataModel *dmo = [self.dataArray objectAtIndex:indexPath.row];
    cell.label.text = dmo.text;
    
    NSLog(@"image: %@", dmo.imageUrl);
    [cell loadImageFromURL:dmo.imageUrl];
 
    return cell;
}

#pragma mark - NSURLConnectionDelegate

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
	[self.responseData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [self.responseData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
	NSString* str = [NSString stringWithFormat:@"Connection failed: %@", [error description]];
    UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:@"Error" message:str delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil] autorelease];
    [alert show];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
	[connection release];
    
	NSString *responseString = [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding];
    self.responseData = nil;
    
    NSDictionary *dictionary = [responseString JSONValue];
    
    NSArray *objects = [dictionary valueForKeyPath:@"feed.entry"];

    for (NSDictionary *dict in objects){
        DataModel *dm = [DataModel dataModelWithDic:dict];
        [self.dataArray addObject:dm];
    }
    
    NSLog(@"Loaded %d objects",[self.dataArray count]);
    
    [self.tableView reloadData];
}


@end
